/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * pantallaConsultar.java
 *
 * Created on 06-ago-2010, 15:44:11
 */

package vista.rrhh;

import controlador.rrhh.GestorConsultarLugarCapacitacion;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import util.NTupla;
import util.SwingPanel;
import util.TablaUtil;
import vista.interfaces.ICallBack;

/**
 *
 * @author Administrador
 */
public class pantallaConsultarLugarCapacitacion extends javax.swing.JInternalFrame implements ICallBack {

    private GestorConsultarLugarCapacitacion gestor;
    private ICallBack win;

    /** Creates new form pantallaConsultar */
    public pantallaConsultarLugarCapacitacion() {
        initComponents();

        gestor = new GestorConsultarLugarCapacitacion(this);

        habilitarVentana();

    }

    public void setCallBack(ICallBack win)
    {
        this.win = win;
    }

    private void habilitarVentana()
    {
        cargarDatosIniciales();

        btnBaja.setEnabled(false);
        btnAlta.setEnabled(false);

    }

    private void refrescarTabla()
    {
        cargarDatosIniciales();
    }

    private void cargarDatosIniciales()
    {
        // Cargo los datos iniciales de la tabla
        ArrayList<NTupla> lista = gestor.mostrarLugaresCapacitacion();
        DefaultTableModel modelo = (DefaultTableModel)tblLista.getModel();

       llenarTabla(lista);
        
    }

    private void llenarTabla(ArrayList<NTupla> lista)
    {
        DefaultTableModel modelo = (DefaultTableModel)tblLista.getModel();
        modelo = TablaUtil.vaciarDefaultTableModel(modelo);

        setCantidadResultados(lista.size());

        Iterator<NTupla> it = lista.iterator();
        while (it.hasNext())
        {
            NTupla  nt = it.next();
            Object[] fila = new Object[3];
            fila[0] = nt;
            String[] data = (String[]) nt.getData();

                fila[1] = data[0];
                fila[2] = data[1];

            modelo.addRow(fila);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtBuscar = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblLista = new javax.swing.JTable();
        btnBaja = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        lblCantResultados = new javax.swing.JLabel();
        btnAlta = new javax.swing.JButton();
        btnNuevo = new javax.swing.JButton();

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Consultar Lugares de Capacitación");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        txtBuscar.setFont(new java.awt.Font("Tahoma", 2, 11));
        txtBuscar.setForeground(new java.awt.Color(102, 102, 102));
        txtBuscar.setText("Buscar...");
        txtBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtBuscarMouseClicked(evt);
            }
        });
        txtBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtBuscarActionPerformed(evt);
            }
        });
        txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtBuscarKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtBuscarKeyTyped(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/search.png"))); // NOI18N

        tblLista.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Dirección", "Estado"
            }
        ));
        tblLista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblListaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblLista);

        btnBaja.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/delete_page.png"))); // NOI18N
        btnBaja.setText("Dar de Baja");
        btnBaja.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBajaActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/text_page.png"))); // NOI18N
        jButton2.setText("Modificar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        lblCantResultados.setFont(new java.awt.Font("Tahoma", 2, 12));
        lblCantResultados.setText("Resultados Encontrados");

        btnAlta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/accept_page.png"))); // NOI18N
        btnAlta.setText("Dar de Alta");
        btnAlta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAltaActionPerformed(evt);
            }
        });

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/add.png"))); // NOI18N
        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblCantResultados, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                        .addComponent(btnNuevo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAlta, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnBaja)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBaja)
                    .addComponent(lblCantResultados)
                    .addComponent(btnAlta)
                    .addComponent(jButton2)
                    .addComponent(btnNuevo))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtBuscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtBuscarMouseClicked

        if(txtBuscar.getText().equals("Buscar..."))
        {
            txtBuscar.setText("");
        }

    }//GEN-LAST:event_txtBuscarMouseClicked

    private void setCantidadResultados(int cant)
    {
        lblCantResultados.setText("Cantidad de Resultados: "+cant);
    }

    private void txtBuscarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyTyped

    }//GEN-LAST:event_txtBuscarKeyTyped

    private void txtBuscarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
        {
            System.out.println("ACTION KEY + "+txtBuscar.getText());
            ArrayList<NTupla> lista = gestor.buscarLugaresCapacitacionPorNombre(txtBuscar.getText());

            llenarTabla(lista);
        }
    }//GEN-LAST:event_txtBuscarKeyPressed

    private void btnBajaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBajaActionPerformed

        int seleccion = JOptionPane.showOptionDialog(
                        this, // Componente padre
                        "¿Está seguro que desea dar de BAJA el Lugar de Capacitación?", //Mensaje
                        "Confirme su acción", // Título
                        JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,    // null para icono por defecto.
                        new Object[] { "Si", "No" },
                        "Si");

        if (seleccion != -1)
        {
           if((seleccion + 1)==1)
           {
                if(tblLista.getSelectedRow()!=-1)
                {
                    // Agrego la fila
                    DefaultTableModel modelo = (DefaultTableModel) tblLista.getModel();
                    NTupla tp = (NTupla) modelo.getValueAt(tblLista.getSelectedRow(),0);

                    if(tp.getId()!=0)
                    {
                        gestor.darBajaLugarCapacitacion(tp.getId());
                    }

                }
           }
        }

    }//GEN-LAST:event_btnBajaActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    /* if(tblLista.getSelectedRow()!=-1)
            {
                // Agrego la fila
                DefaultTableModel modelo = (DefaultTableModel) tblLista.getModel();
                NTupla tp = (NTupla) modelo.getValueAt(tblLista.getSelectedRow(),0);

                if(tp.getId()!=0)
                {
//                    // LLAMO A LA PANTALLA QUE MODIFICA !!
//                    pantallaModificarLugarCapacitacion pmlc = new pantallaModificarLugarCapacitacion(tp.getId());
//                    SwingPanel.getInstance().addWindow(pmlc);
//                    pmlc.setPantalla(this);
//                    pmlc.setVisible(true);
                }

            }*/
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btnAltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAltaActionPerformed

                int seleccion = JOptionPane.showOptionDialog(
                        this, // Componente padre
                        "¿Está seguro que desea dar de ALTA el Lugar de Capacitación?", //Mensaje
                        "Confirme su acción", // Título
                        JOptionPane.YES_NO_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,    // null para icono por defecto.
                        new Object[] { "Si", "No" },
                        "Si");

        if (seleccion != -1)
        {
           if((seleccion + 1)==1)
           {
                if(tblLista.getSelectedRow()!=-1)
                {
                    // Agrego la fila
                    DefaultTableModel modelo = (DefaultTableModel) tblLista.getModel();
                    NTupla tp = (NTupla) modelo.getValueAt(tblLista.getSelectedRow(),0);

                    if(tp.getId()!=0)
                    {
                        gestor.darAltaLugarCapacitacion(tp.getId());
                    }

                }
           }
        }


    }//GEN-LAST:event_btnAltaActionPerformed

    private void tblListaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblListaMouseClicked

        if(tblLista.getSelectedRow()!=-1)
        {
           DefaultTableModel modelo = (DefaultTableModel) tblLista.getModel();
           NTupla tp = (NTupla) modelo.getValueAt(tblLista.getSelectedRow(),0);
           String[] fila = (String[])tp.getData();
           if(fila[1].equals("Alta"))
           {
                btnBaja.setEnabled(true);
                btnAlta.setEnabled(false);
           }
           else
           {
               btnAlta.setEnabled(true);
               btnBaja.setEnabled(false);
           }
        }

    }//GEN-LAST:event_tblListaMouseClicked

    private void txtBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBuscarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtBuscarActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        pantallaRegistrarLugarCapacitacion win = new pantallaRegistrarLugarCapacitacion();
        SwingPanel.getInstance().addWindow(win);
        win.setPantalla(this);
        win.setVisible(true);
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        int FLAG_LUGAR_CAPACITACION = 1;
        win.actualizar(FLAG_LUGAR_CAPACITACION,true);
    }//GEN-LAST:event_formInternalFrameClosing

   /**
     * EL-0015 : No se pudo cargar el listado de Lugares de Capacitación
    *  ME-0008 : Se dio de baja el Lugar de Capacitación
     * @param cod
     */
    public void MostrarMensaje(String cod)
    {
        System.out.println("Se detecto el mensaje: "+cod);
        if(cod.equals("EG-0015"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"No se pudo cargar la lista de Lugares","Error en la Carga",JOptionPane.ERROR_MESSAGE);
        }

        if(cod.equals("MI-0008"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"Se dio de BAJA el Lugar de Capacitación","Atención",JOptionPane.INFORMATION_MESSAGE);
            refrescarTabla();
        }

        if(cod.equals("MI-0009"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"Se dio de ALTA el Lugar de Capacitación","Atención",JOptionPane.INFORMATION_MESSAGE);
            refrescarTabla();
        }

        if(cod.equals("EG-0019"))
        {
            JOptionPane.showMessageDialog(this.getParent(),"No se pudo conectar con la Base de datos para cambiar el estado","Error",JOptionPane.ERROR_MESSAGE);
        }

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlta;
    private javax.swing.JButton btnBaja;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCantResultados;
    private javax.swing.JTable tblLista;
    private javax.swing.JTextField txtBuscar;
    // End of variables declaration//GEN-END:variables

    public void actualizar(int flag, boolean exito) {
        refrescarTabla();
    }

}
